package com.baide.sanguanheyi.weight;

import com.baide.sanguanheyi.config.ThreadManager;
import com.baide.sanguanheyi.interfaces.WeightCallBack;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;

/**
 * 串口数据接收器
 */
@Component
public class WeightAccept implements SerialPortEventListener, Runnable {
    @Autowired
    WeightConfig config;
    // 串口通信管理类
    CommPortIdentifier portId;
    InputStream inputStream; // 从串口来的输入流
    SerialPort serialPort; // 串口的引用
    WeightCallBack callBack;//设置数据回调
    StringBuffer sb = new StringBuffer();

    public void setCallBack(WeightCallBack callBack) {
        this.callBack = callBack;
    }

    @Override
    public void serialEvent(SerialPortEvent serialPortEvent) {
        switch (serialPortEvent.getEventType()) {
            case SerialPortEvent.BI:
            case SerialPortEvent.OE:
            case SerialPortEvent.FE:
            case SerialPortEvent.PE:
            case SerialPortEvent.CD:
            case SerialPortEvent.CTS:
            case SerialPortEvent.DSR:
            case SerialPortEvent.RI:
            case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
                break;
            case SerialPortEvent.DATA_AVAILABLE:// 当有可用数据时读取数据
                byte[] cache = new byte[1024];
                int availableBytes = 0;
                try {
                    availableBytes = inputStream.available();
                    while (availableBytes > 0) {
                        inputStream.read(cache);
                        for (int i = 0; i < cache.length && i < availableBytes; i++) {
                            sb.append((char) cache[i]);
                        }
                        if (callBack != null && sb.length() != 0 && sb.toString().endsWith("\r\n")
                                && sb.toString().endsWith("\n")) {//数据回调到处理方法处
                            String sss = sb.toString().trim().replaceAll("\r\n", "\n");
                            String[] split = sss.split("\n");
                            ThreadManager.getThreadPollProxy().execute(new Runnable() {
                                @Override
                                public void run() {
                                    callBack.weightResult(split[split.length - 1]);
                                }
                            });
                            sb.delete(0, sb.length());
                        }
                        availableBytes = 0;
                    }

                } catch (IOException e) {
                }
            default:
                break;
        }
    }

    public void start() {
        try {
            portId = CommPortIdentifier.getPortIdentifier(config.getPortName());
            //延迟2s启动端口
            serialPort = (SerialPort) portId.open(config.getPortName(), 2000);
            serialPort.addEventListener(this);//添加监听器
            inputStream = serialPort.getInputStream();//获取输入流
            // 设置监听器生效，即：当有数据时通知
            serialPort.notifyOnDataAvailable(true);
            serialPort.setSerialPortParams(9600, //波特率
                    SerialPort.DATABITS_8, //数据位 8
                    SerialPort.STOPBITS_1,//停止位1
                    SerialPort.PARITY_NONE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        start();
    }
}
